﻿using System;
using System.Diagnostics;
using System.Windows.Forms;
using NanoERP.Infrastructure;
using NanoERP.Business.BaseInfo;
using DevComponents.AdvTree;
using NanoERP.Model;
using System.Collections.Generic;
using NanoERP.Common;

namespace NanoERP.BaseInfo
{
    //[Module("FrmSelectProduct")]
    public partial class FrmSelectProduct : ModuleForm
    {
        readonly SysdictableBLL _sysdictablebLl;
        readonly GoodsinfoBLL _goodsInfoBll;
        readonly Dictionary<long, Goodsinfo> _dicUserInfo;
        private const string SeletedCell = "SELECTED";
        readonly bool _isCheckBoxCell;
        public FrmSelectProduct()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 商品选择
        /// </summary>
        /// <param name="isCheckBoxCell">是否显示选择列</param>
        public FrmSelectProduct(bool isCheckBoxCell = false)
        {
            InitializeComponent();

            _goodsInfoBll = new GoodsinfoBLL();
            _sysdictablebLl = new SysdictableBLL();
            _dicUserInfo = new Dictionary<long, Goodsinfo>();
            _isCheckBoxCell = isCheckBoxCell;

            BindTreeView();
            dgvList.Columns[SeletedCell].Visible = isCheckBoxCell;
        }

        /// <summary>
        /// 
        /// </summary>
        void QueryGoods()
        {
            if (dicTree.SelectedNode == null) return;
            var id = int.Parse(dicTree.SelectedNode.Name);
            dgvList.AutoGenerateColumns = false;
            dgvList.DataSource = _goodsInfoBll.Query(id, txtKey.Text.Trim());
        }

        /// <summary>
        /// 绑定商品类别树
        /// </summary>
        void BindTreeView()
        {
            dicTree.Nodes.Clear();

            var sysdic = _sysdictablebLl.Get((int)SysDicEnum.商品信息);
            var firNode = new Node(sysdic.Dicname) { Tag = sysdic, Name = sysdic.Id.ToString(), Image = NanoERP.Properties.Resources.XmlStructure };
            firNode.ExpandAll();
            var firList = _sysdictablebLl.Query(sysdic.Id);
            RecursiveLoopNodes(firList, firNode);

            dicTree.Nodes.Add(firNode);
            if (dicTree.Nodes.Count > 0)
                dicTree.SelectedNode = dicTree.Nodes[0].Nodes.Count > 0 ? dicTree.Nodes[0].Nodes[0] : dicTree.Nodes[0];
        }

        /// <summary>
        /// 递归循环调用
        /// </summary>
        /// <param name="firList">一级树集合</param>
        /// <param name="parentNode">上级节点</param>
        void RecursiveLoopNodes(List<Sysdictable> firList, Node parentNode)
        {
            firList.ForEach(r =>
            {
                var secNode = new Node(r.Dicname) { Tag = r, Name = r.Id.ToString(), Image = NanoERP.Properties.Resources.CreateTableTemplatesGallery };

                parentNode.Nodes.Add(secNode);
                var recList = _sysdictablebLl.Query(r.Id);
                if (recList.Count > 0)
                    RecursiveLoopNodes(recList, secNode);
            });
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (_isCheckBoxCell && _dicUserInfo.Count == 0)
            {
                MessageBox.Show(@"没有选择商品，请重新检索后选择记录！", @"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

            if (!_isCheckBoxCell)
            {
                if (dgvList.CurrentRow == null)
                {
                    MessageBox.Show(@"没有选择商品，请重新检索后选择记录！", @"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }

                var vv = dgvList.CurrentRow.DataBoundItem as Goodsinfo;
                _dicUserInfo.Add(vv.Id, vv);
            }

            this.Tag = _dicUserInfo;
            this.DialogResult = DialogResult.OK;
        }

        private void dicTree_AfterNodeSelect(object sender, AdvTreeNodeEventArgs e)
        {
            QueryGoods();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            if (dgvList.CurrentCell.OwningColumn.Name == SeletedCell)
                return;
            if (dgvList.CurrentRow.Cells[SeletedCell].Value==null||!dgvList.CurrentRow.Cells[SeletedCell].Value.Equals("1"))
                dgvList.CurrentRow.Cells[SeletedCell].Value="1";
            btnSelect_Click(null, null);
        }

        private void dgvList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            ControlUtil.DataGridRowPostPaint(sender, e);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var sysdic = dicTree.SelectedNode.Tag as Sysdictable;

            var f = new FrmProductInfo(sysdic);
            if (f.ShowDialog() == DialogResult.OK)
            {
                QueryGoods();
            }
        }

        private void txtKey_TextChanged(object sender, EventArgs e)
        {
            QueryGoods();
        }

        private void dgvList_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvList.IsCurrentCellDirty) dgvList.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dgvList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;

            if (dgvList.Columns[e.ColumnIndex].Name == SeletedCell)
            {
                var currRow = dgvList.Rows[e.RowIndex];
                var checkCell = (DataGridViewCheckBoxCell)currRow.Cells[SeletedCell];
                var vv = currRow.DataBoundItem as Goodsinfo;

                if (checkCell.Value.Equals("1"))
                    _dicUserInfo.Add(vv.Id, vv);
                else
                    _dicUserInfo.Remove(vv.Id);

                dgvList.Invalidate();
            }
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
